const express = require('express');
const { handleError, executeQuery, formatDateTime } = require('../utils');
const router = express.Router();

// 查询用户反馈列表
router.post('/list', async (req, res) => {
    const { page = 1, pageSize = 10, search = '' } = req.body;
    const offset = (page - 1) * pageSize;
    const limit = pageSize;

    const searchQuery = `%${search}%`;

    const totalQuery = `
        SELECT COUNT(*) AS total
        FROM user_feedback
        WHERE content LIKE ? OR admin_reply LIKE ?
    `;

    const query = `
        SELECT * 
        FROM user_feedback
        WHERE content LIKE ? OR admin_reply LIKE ?
        LIMIT ${limit} OFFSET ${offset}
    `;

    try {
        const totalResult = await executeQuery(totalQuery, [searchQuery, searchQuery]);
        const total = totalResult[0].total;
        const feedbacks = await executeQuery(query, [searchQuery, searchQuery]);

        feedbacks.forEach(feedback => {
            feedback.created_at = formatDateTime(feedback.created_at);
            feedback.updated_at = formatDateTime(feedback.updated_at);
        });

        res.json({ total, page, pageSize, data: feedbacks });
    } catch (error) {
        handleError(error, res);
    }
});

// 提交用户反馈
router.post('/submit', async (req, res) => {
    const { user_id, feedback_type, content, journal_id } = req.body;

    // 如果反馈类型为“期刊”，则必须提供 journal_id
    if (feedback_type === 'journal' && !journal_id) {
        return res.status(400).json({ message: '期刊反馈必须关联期刊ID' });
    }

    const query = `
        INSERT INTO user_feedback (user_id, feedback_type, content, journal_id, created_at, updated_at)
        VALUES (?, ?, ?, ?, NOW(), NOW());
    `;

    try {
        await executeQuery(query, [user_id, feedback_type, content, journal_id || null]);
        res.json({ message: '反馈提交成功' });
    } catch (error) {
        handleError(error, res);
    }
});

// 管理员回复反馈
router.post('/reply', async (req, res) => {
    const { feedback_id, admin_reply } = req.body;

    const query = `
        UPDATE user_feedback
        SET admin_reply = ?, status = 'replied', updated_at = NOW()
        WHERE feedback_id = ?;
    `;

    try {
        await executeQuery(query, [admin_reply, feedback_id]);
        res.json({ message: '回复成功' });
    } catch (error) {
        handleError(error, res);
    }
});

// 删除反馈
router.post('/delete', async (req, res) => {
    const { feedback_id } = req.body;

    const query = 'DELETE FROM user_feedback WHERE feedback_id = ?';

    try {
        await executeQuery(query, [feedback_id]);
        res.json({ message: '反馈已删除' });
    } catch (error) {
        handleError(error, res);
    }
});

module.exports = router;
